package com.bigchun.seeland;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;

import myapp.MyApp;
import runtimepermissions.PermissionsManager;
import runtimepermissions.PermissionsResultAction;
import util.MyLog;
import util.PreferenceUtil;
import util.RequestManager;

public class SplashActivity extends BaseActivity {


    private MyApp myApp;
    private Context context;
    private SharedPreferences spuserInfo;
    private String token;
    private String apptype = "0";
    private ImageView img_logo;
    private JSONObject textData;

    private TextView tv_name;
    //    private ContentDataBean.DataBean textData = new ContentDataBean.DataBean();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 打包注意事项
         * 1，启动页的默认的apptype要修改，木头为0，熙然为1
         * 2，熙然默认英文
         * 3，app名字需要更改
         * 4，glideutils需要更改默认图片
         *
          */



//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏
//        getSupportActionBar().hide();//隐藏标题栏
        setContentView(R.layout.activity_splash);
        myApp = (MyApp) getApplicationContext();
        context = this;
        spuserInfo = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
        token = spuserInfo.getString("token", "");
        apptype = spuserInfo.getString("apptype", "");
        PreferenceUtil.commitString("language", "en");//en   zh
        //如果本地没有存储默认的方式，默认木头为0，熙然为1     GlideUtils类中，占位图也要更换
        String defaultApptype = "1";
        if ("".equals(apptype)){
            spuserInfo.edit().putString("apptype",defaultApptype).commit();
        }
        apptype = spuserInfo.getString("apptype", defaultApptype);

        getContentData();


        img_logo = findViewById(R.id.img_logo);
        tv_name = findViewById(R.id.tv_name);



        /**
         * 请求所有必要的权限----原理就是获取清单文件中申请的权限
         */
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                Toast.makeText(SplashActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
                Toast.makeText(SplashActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });


    }



    /**
     * 获取配置信息
     */
    private void getconfigData() {

        String url = myApp.getWebConfig()+"/api/index/my_config";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token",token);
        paramsMap.put("is_material",apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 4;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    String domain = data.getString("domain");
                    String urlstr = data.getString("url");
                    String z_about = data.getString("z_about");
                    String j_about = data.getString("j_about");
                    String e_about = data.getString("e_about");
                    String z_formula = data.getString("z_formula");
                    spuserInfo.edit().putString("domain",domain).commit();
                    spuserInfo.edit().putString("urlstr",urlstr).commit();
                    spuserInfo.edit().putString("z_about",z_about).commit();
                    spuserInfo.edit().putString("e_about",e_about).commit();
                    spuserInfo.edit().putString("j_about",j_about).commit();
                    spuserInfo.edit().putString("z_formula",z_formula).commit();
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }
    /**
     * 获取配置信息
     */
    private void getContentData() {
        String string = PreferenceUtil.getString("language", "");
        if ("".equals(string)){
            Locale locale = Locale.getDefault();
            string = locale.getLanguage();
            switchLanguage(string);
        }
        MyLog.e("手机系统语言","语言     "+string);
        String url = myApp.getWebConfig()+"/api/index/apptran";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("lang",string);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    textData = jsonObject.getJSONObject("data");
//                    textData = new Gson().fromJson(data.toString(), new TypeToken<ContentDataBean.DataBean>() {
//                    }.getType());
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }else{
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Intent intent = null;
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    getconfigData();
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();

                    break;
                case 1:



                    getconfigData();
                    try {
                        Toast.makeText(context, textData.getString("net_error"), Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 2:
                    Thread myThread2=new Thread(){//创建子线程
                        @Override
                        public void run() {
                            try{
                                sleep(2000);//使程序休眠五秒
                                if (!"".equals(token)){
                                    Intent it=new Intent(getApplicationContext(),MainActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }else{
                                    Intent it=new Intent(getApplicationContext(),LoginActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    };
                    myThread2.start();//启动线程
                    break;
                case 3:
                    getconfigData();
                    spuserInfo.edit().putString("textData",textData.toString()).commit();
                    try {
                        if ("0".equals(apptype)){
                            tv_name.setText(textData.getString("splash_wood"));
                            img_logo.setImageResource(R.mipmap.icon_wood);
                        }else if ("1".equals(apptype)){
                            tv_name.setText(textData.getString("splash_xiran"));
                            img_logo.setImageResource(R.mipmap.icon_xiran);
                        }
                    }catch (Exception e){

                    }

                    break;
                case 4:
                    String strstr = (String) msg.obj;
                    Toast.makeText(context, strstr, Toast.LENGTH_LONG).show();
                    Thread myThread=new Thread(){//创建子线程
                        @Override
                        public void run() {
                            try{
                                sleep(2000);//使程序休眠五秒
                                if (!"".equals(token)){
                                    Intent it=new Intent(getApplicationContext(),MainActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }else{
                                    Intent it=new Intent(getApplicationContext(),LoginActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    };
                    myThread.start();//启动线程
                    break;
                case 5:

Thread myThread1=new Thread(){//创建子线程
                        @Override
                        public void run() {
                            try{
                                sleep(2000);//使程序休眠五秒
                                if (!"".equals(token)){
                                    Intent it=new Intent(getApplicationContext(),MainActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }else{
                                    Intent it=new Intent(getApplicationContext(),LoginActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    };
                    myThread1.start();//启动线程
                    break;
                case 12:
                    Log.e("无网络","无网络");
                    if (!"".equals(token)){
                        Intent it=new Intent(getApplicationContext(),MainActivity.class);//启动MainActivity
                        startActivity(it);
                        finish();//关闭当前活动
                    }else{
                        Intent it=new Intent(getApplicationContext(),LoginActivity.class);//启动MainActivity
                        startActivity(it);
                        finish();//关闭当前活动
                    }
                    break;
            }
        }
    };



}
